<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>工业物联网数据采集系统 - 现代化仪表盘</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        :root {
            --primary-color: #2c3e50;
            --success-color: #27ae60;
            --danger-color: #e74c3c;
            --warning-color: #f39c12;
            --info-color: #3498db;
            --dark-bg: #1a1a1a;
            --card-bg: rgba(255, 255, 255, 0.95);
        }
        
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        .dashboard-card {
            border-radius: 20px;
            box-shadow: 0 15px 35px rgba(0,0,0,0.1);
            transition: all 0.4s ease;
            border: none;
            backdrop-filter: blur(15px);
            background: var(--card-bg);
            overflow: hidden;
        }
        
        .dashboard-card:hover {
            transform: translateY(-10px);
            box-shadow: 0 25px 50px rgba(0,0,0,0.2);
        }
        
        .stat-card {
            background: linear-gradient(135deg, var(--card-color-1), var(--card-color-2));
            color: white;
            border-radius: 25px;
            padding: 30px;
            margin-bottom: 25px;
            transition: all 0.4s ease;
            position: relative;
            overflow: hidden;
        }
        
        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: linear-gradient(45deg, transparent, rgba(255,255,255,0.1), transparent);
            transform: translateX(-100%);
            transition: transform 0.6s;
        }
        
        .stat-card:hover::before {
            transform: translateX(100%);
        }
        
        .stat-card:hover {
            transform: scale(1.05) rotateY(5deg);
        }
        
        .stat-card.success {
            --card-color-1: #27ae60;
            --card-color-2: #2ecc71;
        }
        
        .stat-card.danger {
            --card-color-1: #e74c3c;
            --card-color-2: #c0392b;
        }
        
        .stat-card.warning {
            --card-color-1: #f39c12;
            --card-color-2: #e67e22;
        }
        
        .stat-card.info {
            --card-color-1: #3498db;
            --card-color-2: #2980b9;
        }
        
        .status-indicator {
            width: 14px;
            height: 14px;
            border-radius: 50%;
            display: inline-block;
            margin-right: 10px;
            position: relative;
        }
        
        .status-indicator::after {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            border-radius: 50%;
            animation: ripple 2s infinite;
        }
        
        @keyframes ripple {
            0% {
                transform: scale(1);
                opacity: 1;
            }
            100% {
                transform: scale(2);
                opacity: 0;
            }
        }
        
        .status-online { 
            background-color: var(--success-color);
        }
        .status-online::after {
            background-color: var(--success-color);
        }
        
        .status-offline { 
            background-color: var(--danger-color);
        }
        .status-offline::after {
            background-color: var(--danger-color);
        }
        
        .status-warning { 
            background-color: var(--warning-color);
        }
        .status-warning::after {
            background-color: var(--warning-color);
        }
        
        .navbar {
            background: linear-gradient(135deg, var(--primary-color), #34495e) !important;
            box-shadow: 0 6px 30px rgba(0,0,0,0.15);
            backdrop-filter: blur(10px);
        }
        
        .card-header {
            background: linear-gradient(135deg, var(--primary-color), #34495e);
            color: white;
            border-radius: 20px 20px 0 0 !important;
            border: none;
            padding: 20px 30px;
        }
        
        .btn-modern {
            border-radius: 30px;
            padding: 10px 25px;
            transition: all 0.3s ease;
            border: none;
            font-weight: 500;
            position: relative;
            overflow: hidden;
        }
        
        .btn-modern:hover {
            transform: translateY(-2px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
        }
        
        .table-modern {
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 5px 15px rgba(0,0,0,0.05);
        }
        
        .table-modern tbody tr {
            transition: all 0.3s ease;
        }
        
        .table-modern tbody tr:hover {
            background: linear-gradient(90deg, rgba(52, 152, 219, 0.1), rgba(155, 89, 182, 0.1));
            transform: scale(1.01);
        }
        
        .loading-animation {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid rgba(255,255,255,.3);
            border-radius: 50%;
            border-top-color: #fff;
            animation: spin 1s ease-in-out infinite;
        }
        
        @keyframes spin {
            to { transform: rotate(360deg); }
        }
        
        .chart-container {
            position: relative;
            height: 350px;
            margin: 25px 0;
        }
        
        .device-badge {
            padding: 8px 18px;
            border-radius: 25px;
            font-size: 0.85em;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
        }
        
        .alert-modern {
            border-radius: 20px;
            border: none;
            box-shadow: 0 8px 25px rgba(0,0,0,0.1);
            backdrop-filter: blur(10px);
        }
        
        .pulse-animation {
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }
        
        .gradient-text {
            background: linear-gradient(135deg, #667eea, #764ba2);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }
        
        .floating-element {
            animation: float 3s ease-in-out infinite;
        }
        
        @keyframes float {
            0%, 100% { transform: translateY(0px); }
            50% { transform: translateY(-10px); }
        }
        
        .glass-effect {
            background: rgba(255, 255, 255, 0.1);
            backdrop-filter: blur(20px);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <nav class="navbar navbar-expand-lg navbar-dark fixed-top">
        <div class="container-fluid">
            <a class="navbar-brand fw-bold" href="/">
                <i class="fas fa-industry floating-element"></i>
                工业物联网数据采集系统
            </a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav">
                <span class="navbar-toggler-icon"></span>
            </button>
            <div class="collapse navbar-collapse" id="navbarNav">
                <ul class="navbar-nav me-auto">
                    <li class="nav-item">
                        <a class="nav-link" href="/">
                            <i class="fas fa-home"></i> 主控台
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link active" href="/dashboard">
                            <i class="fas fa-chart-line"></i> 监控仪表盘
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/device-manager">
                            <i class="fas fa-cogs"></i> 设备管理
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/device-config">
                            <i class="fas fa-plus-circle"></i> 快速配置
                        </a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="/status-test">
                            <i class="fas fa-stethoscope"></i> 系统诊断
                        </a>
                    </li>
                </ul>
                <div class="navbar-nav">
                    <span class="navbar-text me-4">
                        <i class="fas fa-clock"></i>
                        <span id="current-time" class="fw-bold"></span>
                    </span>
                    <span class="navbar-text glass-effect px-3 py-1 rounded-pill">
                        <span class="status-indicator status-online"></span>
                        系统运行中
                    </span>
                </div>
            </div>
        </div>
    </nav>

    <div class="container-fluid" style="padding-top: 90px;">
        <!-- 系统状态横幅 -->
        <div class="row mb-4">
            <div class="col-12">
                <div class="alert alert-modern alert-info glass-effect" role="alert">
                    <div class="d-flex align-items-center">
                        <div class="loading-animation me-3"></div>
                        <div class="flex-grow-1">
                            <strong><i class="fas fa-server"></i> 系统状态:</strong> 正常运行 | 
                            <strong><i class="fab fa-python"></i> Python版本:</strong> 3.13+ | 
                            <strong><i class="fas fa-layer-group"></i> 虚拟环境:</strong> 已激活 |
                            <strong><i class="fas fa-sync-alt"></i> 最后更新:</strong> <span id="last-update">刚刚</span>
                        </div>
                        <button class="btn btn-outline-light btn-sm btn-modern" onclick="refreshAllData()">
                            <i class="fas fa-refresh"></i> 全部刷新
                        </button>
                    </div>
                </div>
            </div>
        </div>

        <!-- 统计卡片 -->
        <div class="row mb-5">
            <div class="col-lg-3 col-md-6 mb-3">
                <div class="stat-card success">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="text-uppercase fw-bold opacity-75 mb-2">在线设备</h6>
                            <h1 class="mb-1 fw-bold pulse-animation" id="online-devices">0</h1>
                            <small class="opacity-75">设备正常连接</small>
                        </div>
                        <div>
                            <i class="fas fa-check-circle fa-4x opacity-50"></i>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-md-6 mb-3">
                <div class="stat-card danger">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="text-uppercase fw-bold opacity-75 mb-2">离线设备</h6>
                            <h1 class="mb-1 fw-bold pulse-animation" id="offline-devices">0</h1>
                            <small class="opacity-75">设备连接异常</small>
                        </div>
                        <div>
                            <i class="fas fa-times-circle fa-4x opacity-50"></i>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-md-6 mb-3">
                <div class="stat-card warning">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="text-uppercase fw-bold opacity-75 mb-2">活跃报警</h6>
                            <h1 class="mb-1 fw-bold pulse-animation" id="active-alarms">0</h1>
                            <small class="opacity-75">需要处理的报警</small>
                        </div>
                        <div>
                            <i class="fas fa-exclamation-triangle fa-4x opacity-50"></i>
                        </div>
                    </div>
                </div>
            </div>
            
            <div class="col-lg-3 col-md-6 mb-3">
                <div class="stat-card info">
                    <div class="d-flex justify-content-between align-items-center">
                        <div>
                            <h6 class="text-uppercase fw-bold opacity-75 mb-2">数据点总数</h6>
                            <h1 class="mb-1 fw-bold pulse-animation" id="total-tags">0</h1>
                            <small class="opacity-75">配置的监控点</small>
                        </div>
                        <div>
                            <i class="fas fa-database fa-4x opacity-50"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- 主要内容区域 -->
        <div class="row">
            <!-- 设备状态表格 -->
            <div class="col-xl-8 col-lg-7">
                <div class="card dashboard-card">
                    <div class="card-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <h5 class="mb-0">
                                <i class="fas fa-list-alt me-2"></i> 设备状态监控
                            </h5>
                            <div class="btn-group">
                                <button class="btn btn-outline-light btn-sm btn-modern" onclick="refreshDevices()">
                                    <i class="fas fa-sync-alt"></i> 刷新
                                </button>
                                <button class="btn btn-outline-light btn-sm btn-modern" onclick="exportDeviceData()">
                                    <i class="fas fa-download"></i> 导出
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="card-body p-0">
                        <div class="table-responsive">
                            <table class="table table-modern table-hover align-middle mb-0" id="devices-table">
                                <thead class="table-light">
                                    <tr>
                                        <th class="px-4 py-3"><i class="fas fa-tag me-2"></i>设备名称</th>
                                        <th><i class="fas fa-info-circle me-2"></i>描述</th>
                                        <th><i class="fas fa-layer-group me-2"></i>协议</th>
                                        <th><i class="fas fa-signal me-2"></i>状态</th>
                                        <th><i class="fas fa-list-ol me-2"></i>数据点</th>
                                        <th><i class="fas fa-tools me-2"></i>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="devices-tbody">
                                    <tr>
                                        <td colspan="6" class="text-center py-5">
                                            <div class="loading-animation me-2"></div>
                                            正在加载设备数据...
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 系统信息侧边栏 -->
            <div class="col-xl-4 col-lg-5">
                <!-- 系统性能 -->
                <div class="card dashboard-card mb-4">
                    <div class="card-header">
                        <h5 class="mb-0">
                            <i class="fas fa-server me-2"></i> 系统性能
                        </h5>
                    </div>
                    <div class="card-body">
                        <div class="row text-center">
                            <div class="col-6">
                                <div class="border-end">
                                    <h3 class="text-success mb-1 fw-bold">99.9%</h3>
                                    <small class="text-muted">系统可用性</small>
                                </div>
                            </div>
                            <div class="col-6">
                                <h3 class="text-info mb-1 fw-bold" id="cpu-usage">5%</h3>
                                <small class="text-muted">CPU 使用率</small>
                            </div>
                        </div>
                        <hr class="my-3">
                        <div class="row text-center">
                            <div class="col-6">
                                <div class="border-end">
                                    <h3 class="text-warning mb-1 fw-bold" id="memory-usage">150MB</h3>
                                    <small class="text-muted">内存使用</small>
                                </div>
                            </div>
                            <div class="col-6">
                                <h3 class="text-primary mb-1 fw-bold" id="data-rate">1.2K/s</h3>
                                <small class="text-muted">数据采集率</small>
                            </div>
                        </div>
                        <div class="mt-3">
                            <div class="progress" style="height: 8px;">
                                <div class="progress-bar bg-success" role="progressbar" style="width: 75%"></div>
                            </div>
                            <small class="text-muted">整体健康度: 75%</small>
                        </div>
                    </div>
                </div>
                
                <!-- 最新报警 -->
                <div class="card dashboard-card">
                    <div class="card-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <h5 class="mb-0">
                                <i class="fas fa-bell me-2"></i> 最新报警
                            </h5>
                            <span class="badge bg-warning rounded-pill">5</span>
                        </div>
                    </div>
                    <div class="card-body">
                        <div id="recent-alarms">
                            <div class="text-center text-muted py-4">
                                <i class="fas fa-check-circle fa-3x mb-3 text-success"></i>
                                <p class="mb-0 fw-bold">当前无活跃报警</p>
                                <small class="text-muted">系统运行正常</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 数据趋势图表 -->
        <div class="row mt-5">
            <div class="col-12">
                <div class="card dashboard-card">
                    <div class="card-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <h5 class="mb-0">
                                <i class="fas fa-chart-area me-2"></i> 数据采集趋势
                            </h5>
                            <div class="btn-group" role="group">
                                <input type="radio" class="btn-check" name="timeRange" id="range1h" checked>
                                <label class="btn btn-outline-light btn-sm" for="range1h">1小时</label>
                                
                                <input type="radio" class="btn-check" name="timeRange" id="range24h">
                                <label class="btn btn-outline-light btn-sm" for="range24h">24小时</label>
                                
                                <input type="radio" class="btn-check" name="timeRange" id="range7d">
                                <label class="btn btn-outline-light btn-sm" for="range7d">7天</label>
                            </div>
                        </div>
                    </div>
                    <div class="card-body">
                        <div class="chart-container">
                            <canvas id="dataChart"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 设备详情模态框 -->
    <div class="modal fade" id="deviceModal" tabindex="-1">
        <div class="modal-dialog modal-xl">
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title">
                        <i class="fas fa-microchip me-2"></i> 设备详情
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body p-0">
                    <div id="device-details" class="p-4">
                        <!-- 设备详情内容 -->
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary btn-modern" data-bs-dismiss="modal">
                        <i class="fas fa-times"></i> 关闭
                    </button>
                    <button type="button" class="btn btn-primary btn-modern">
                        <i class="fas fa-download"></i> 导出数据
                    </button>
                    <button type="button" class="btn btn-success btn-modern">
                        <i class="fas fa-sync-alt"></i> 刷新设备
                    </button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 全局变量
        let dataChart = null;
        let refreshInterval = null;
        let deviceData = [];
        
        // 更新当前时间
        function updateTime() {
            const now = new Date();
            const timeString = now.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit',
                second: '2-digit'
            });
            document.getElementById('current-time').textContent = timeString;
        }
        
        // 全部刷新
        async function refreshAllData() {
            await Promise.all([
                refreshDevices(),
                loadAlarms(),
                updateSystemStats()
            ]);
            document.getElementById('last-update').textContent = new Date().toLocaleTimeString('zh-CN');
            showNotification('数据刷新成功', 'success');
        }
        
        // 刷新设备数据
        async function refreshDevices() {
            try {
                const response = await fetch('/api/devices');
                const data = await response.json();
                
                if (data.success && Array.isArray(data.data)) {
                    deviceData = data.data;
                    updateDeviceStats(data.data);
                    updateDevicesTable(data.data);
                } else {
                    console.error('API 返回格式错误:', data);
                    showNotification('设备数据格式错误', 'error');
                }
            } catch (error) {
                console.error('加载设备数据失败:', error);
                showNotification('设备数据加载失败，请检查网络连接', 'error');
                // 显示默认数据
                updateDevicesTable([]);
            }
        }
        
        // 更新设备统计
        function updateDeviceStats(devices) {
            let onlineCount = 0;
            let offlineCount = 0;
            let totalTags = 0;
            
            devices.forEach(device => {
                if (device.connection_status === 'connected') {
                    onlineCount++;
                } else {
                    offlineCount++;
                }
                totalTags += device.data_points ? device.data_points.length : 0;
            });
            
            // 使用动画效果更新数字
            animateCounter('online-devices', onlineCount);
            animateCounter('offline-devices', offlineCount);
            animateCounter('total-tags', totalTags);
        }
        
        // 数字动画计数器
        function animateCounter(elementId, targetValue) {
            const element = document.getElementById(elementId);
            const currentValue = parseInt(element.textContent) || 0;
            const increment = targetValue > currentValue ? 1 : -1;
            const duration = 1000; // 1秒动画
            const steps = Math.abs(targetValue - currentValue);
            const stepTime = steps > 0 ? duration / steps : 0;
            
            if (steps === 0) return;
            
            let current = currentValue;
            const timer = setInterval(() => {
                current += increment;
                element.textContent = current;
                
                if (current === targetValue) {
                    clearInterval(timer);
                }
            }, stepTime);
        }
        
        // 更新设备表格
        function updateDevicesTable(devices) {
            const tbody = document.getElementById('devices-tbody');
            
            if (devices.length === 0) {
                tbody.innerHTML = `
                    <tr>
                        <td colspan="6" class="text-center py-5 text-muted">
                            <i class="fas fa-inbox fa-3x mb-3"></i>
                            <p class="mb-0 fw-bold">暂无设备配置</p>
                            <small>请检查设备配置文件</small>
                        </td>
                    </tr>
                `;
                return;
            }
            
            tbody.innerHTML = devices.map(device => {
                const statusInfo = getStatusInfo(device.connection_status);
                const protocolBadge = getProtocolBadge(device.type);
                
                return `
                    <tr class="device-row" data-device="${device.name}">
                        <td class="px-4">
                            <div class="d-flex align-items-center">
                                <span class="status-indicator ${statusInfo.class}"></span>
                                <div>
                                    <strong class="text-dark">${device.name}</strong>
                                    <br><small class="text-muted">${device.description || '无描述'}</small>
                                </div>
                            </div>
                        </td>
                        <td>
                            <span class="text-muted">${device.description || '-'}</span>
                        </td>
                        <td>${protocolBadge}</td>
                        <td>
                            <span class="badge ${statusInfo.badgeClass} rounded-pill">
                                ${statusInfo.text}
                            </span>
                        </td>
                        <td>
                            <span class="badge bg-info rounded-pill">
                                ${device.data_points ? device.data_points.length : 0}
                            </span>
                        </td>
                        <td>
                            <div class="btn-group btn-group-sm">
                                <button class="btn btn-outline-primary btn-sm" 
                                        onclick="showDeviceDetails('${device.name}')" 
                                        title="查看详情">
                                    <i class="fas fa-eye"></i>
                                </button>
                                <button class="btn btn-outline-success btn-sm" 
                                        onclick="refreshDevice('${device.name}')" 
                                        title="刷新设备">
                                    <i class="fas fa-sync-alt"></i>
                                </button>
                                <button class="btn btn-outline-info btn-sm" 
                                        onclick="showDeviceChart('${device.name}')" 
                                        title="查看图表">
                                    <i class="fas fa-chart-line"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                `;
            }).join('');
        }
        
        // 获取状态信息
        function getStatusInfo(status) {
            const statusMap = {
                'connected': { 
                    class: 'status-online', 
                    text: '在线', 
                    badgeClass: 'bg-success' 
                },
                'connecting': { 
                    class: 'status-warning', 
                    text: '连接中', 
                    badgeClass: 'bg-warning' 
                },
                'error': { 
                    class: 'status-offline', 
                    text: '错误', 
                    badgeClass: 'bg-danger' 
                },
                'disconnected': { 
                    class: 'status-offline', 
                    text: '离线', 
                    badgeClass: 'bg-secondary' 
                }
            };
            return statusMap[status] || statusMap['disconnected'];
        }
        
        // 获取协议徽章
        function getProtocolBadge(type) {
            const badges = {
                'modbus': '<span class="device-badge bg-primary text-white">MODBUS</span>',
                'opcua': '<span class="device-badge bg-success text-white">OPC UA</span>',
                'mqtt': '<span class="device-badge bg-info text-white">MQTT</span>',
                's7': '<span class="device-badge bg-warning text-dark">S7</span>',
                'http': '<span class="device-badge bg-secondary text-white">HTTP</span>'
            };
            return badges[type?.toLowerCase()] || 
                   `<span class="device-badge bg-light text-dark">${(type || 'UNKNOWN').toUpperCase()}</span>`;
        }
        
        // 显示设备详情
        async function showDeviceDetails(deviceName) {
            try {
                const [statusResponse, dataResponse] = await Promise.all([
                    fetch(`/api/device/${deviceName}/status`),
                    fetch(`/api/device/${deviceName}/data`)
                ]);
                
                const statusData = await statusResponse.json();
                const realTimeData = await dataResponse.json();
                
                const device = deviceData.find(d => d.name === deviceName);
                
                const modalBody = document.getElementById('device-details');
                modalBody.innerHTML = `
                    <div class="row">
                        <div class="col-md-6">
                            <div class="card border-0 shadow-sm">
                                <div class="card-header bg-primary text-white">
                                    <h6 class="mb-0"><i class="fas fa-info-circle me-2"></i>设备信息</h6>
                                </div>
                                <div class="card-body">
                                    <table class="table table-borderless">
                                        <tr><td><strong>设备名称:</strong></td><td>${deviceName}</td></tr>
                                        <tr><td><strong>协议类型:</strong></td><td>${getProtocolBadge(device?.type || 'unknown')}</td></tr>
                                        <tr><td><strong>连接状态:</strong></td><td>${getStatusInfo(statusData.data?.connection_status || 'unknown').text}</td></tr>
                                        <tr><td><strong>轮询间隔:</strong></td><td>${device?.polling_interval || 'N/A'}s</td></tr>
                                        <tr><td><strong>数据点数:</strong></td><td>${device?.data_points?.length || 0}</td></tr>
                                        <tr><td><strong>最后通信:</strong></td><td>${statusData.data?.last_communication || '无'}</td></tr>
                                    </table>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="card border-0 shadow-sm">
                                <div class="card-header bg-success text-white">
                                    <h6 class="mb-0"><i class="fas fa-chart-line me-2"></i>实时数据</h6>
                                </div>
                                <div class="card-body" style="max-height: 300px; overflow-y: auto;">
                                    ${realTimeData.success && realTimeData.data?.length > 0 
                                        ? `<div class="table-responsive">
                                            <table class="table table-sm table-striped">
                                                <thead>
                                                    <tr>
                                                        <th>标签名</th>
                                                        <th>当前值</th>
                                                        <th>质量</th>
                                                        <th>时间</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    ${realTimeData.data.map(tag => `
                                                        <tr>
                                                            <td><code class="text-primary">${tag.tag_name}</code></td>
                                                            <td><strong>${tag.value !== null ? tag.value : 'NULL'}</strong></td>
                                                            <td><span class="badge ${tag.quality === 'GOOD' ? 'bg-success' : 'bg-danger'}">${tag.quality}</span></td>
                                                            <td><small>${new Date(tag.timestamp).toLocaleTimeString()}</small></td>
                                                        </tr>
                                                    `).join('')}
                                                </tbody>
                                            </table>
                                        </div>`
                                        : `<div class="text-center text-muted py-4">
                                            <i class="fas fa-database fa-2x mb-2"></i>
                                            <p class="mb-0">暂无实时数据</p>
                                            <small>设备可能未连接或无数据点配置</small>
                                        </div>`
                                    }
                                </div>
                            </div>
                        </div>
                    </div>
                `;
                
                const modal = new bootstrap.Modal(document.getElementById('deviceModal'));
                modal.show();
            } catch (error) {
                console.error('加载设备详情失败:', error);
                showNotification('设备详情加载失败', 'error');
            }
        }
        
        // 刷新单个设备
        async function refreshDevice(deviceName) {
            showNotification(`正在刷新设备 ${deviceName}...`, 'info');
            // 这里可以添加单个设备刷新的API调用
            setTimeout(() => {
                showNotification(`设备 ${deviceName} 刷新完成`, 'success');
            }, 2000);
        }
        
        // 显示设备图表
        function showDeviceChart(deviceName) {
            showNotification(`正在准备设备 ${deviceName} 的数据图表...`, 'info');
            // 这里可以添加设备图表显示逻辑
        }
        
        // 导出设备数据
        function exportDeviceData() {
            showNotification('正在准备导出数据...', 'info');
            // 这里可以添加数据导出逻辑
        }
        
        // 加载报警数据
        async function loadAlarms() {
            try {
                const response = await fetch('/api/alarms');
                const data = await response.json();
                
                if (data.success) {
                    animateCounter('active-alarms', data.data.active.length);
                    updateRecentAlarms(data.data.active.slice(0, 5));
                }
            } catch (error) {
                console.error('加载报警数据失败:', error);
            }
        }
        
        // 更新最新报警显示
        function updateRecentAlarms(alarms) {
            const container = document.getElementById('recent-alarms');
            
            if (alarms.length === 0) {
                container.innerHTML = `
                    <div class="text-center text-muted py-4">
                        <i class="fas fa-check-circle fa-3x mb-3 text-success"></i>
                        <p class="mb-0 fw-bold">当前无活跃报警</p>
                        <small class="text-muted">系统运行正常</small>
                    </div>
                `;
                return;
            }
            
            container.innerHTML = alarms.map((alarm, index) => `
                <div class="alert alert-warning alert-sm mb-2 border-0 shadow-sm" style="animation-delay: ${index * 0.1}s;">
                    <div class="d-flex justify-content-between align-items-start">
                        <div class="flex-grow-1">
                            <div class="d-flex align-items-center mb-1">
                                <span class="badge bg-danger me-2">${alarm.level}</span>
                                <strong class="text-dark">${alarm.device_name}</strong>
                            </div>
                            <small class="text-muted d-block">${alarm.message}</small>
                        </div>
                        <small class="text-muted ms-2">
                            ${new Date(alarm.timestamp).toLocaleTimeString('zh-CN')}
                        </small>
                    </div>
                </div>
            `).join('');
        }
        
        // 更新系统统计
        async function updateSystemStats() {
            try {
                const response = await fetch('/api/system/status');
                const data = await response.json();
                
                if (data.success) {
                    // 更新系统性能指标
                    document.getElementById('cpu-usage').textContent = `${data.data.cpu_usage || 5}%`;
                    document.getElementById('memory-usage').textContent = `${data.data.memory_usage || 150}MB`;
                    document.getElementById('data-rate').textContent = `${data.data.data_rate || '1.2K'}/s`;
                }
            } catch (error) {
                console.error('获取系统状态失败:', error);
            }
        }
        
        // 初始化图表
        function initChart() {
            const ctx = document.getElementById('dataChart').getContext('2d');
            
            // 创建渐变背景
            const gradient = ctx.createLinearGradient(0, 0, 0, 400);
            gradient.addColorStop(0, 'rgba(75, 192, 192, 0.4)');
            gradient.addColorStop(1, 'rgba(75, 192, 192, 0.0)');
            
            dataChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: generateTimeLabels(),
                    datasets: [{
                        label: '数据采集率',
                        data: generateRandomData(24),
                        borderColor: 'rgb(75, 192, 192)',
                        backgroundColor: gradient,
                        tension: 0.4,
                        fill: true,
                        pointBackgroundColor: 'rgb(75, 192, 192)',
                        pointBorderColor: '#fff',
                        pointBorderWidth: 2,
                        pointRadius: 4
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            mode: 'index',
                            intersect: false,
                            backgroundColor: 'rgba(0, 0, 0, 0.8)',
                            titleColor: '#fff',
                            bodyColor: '#fff',
                            borderColor: 'rgb(75, 192, 192)',
                            borderWidth: 1
                        }
                    },
                    scales: {
                        x: {
                            display: true,
                            grid: {
                                display: false
                            }
                        },
                        y: {
                            display: true,
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(0, 0, 0, 0.1)'
                            }
                        }
                    },
                    interaction: {
                        mode: 'nearest',
                        axis: 'x',
                        intersect: false
                    }
                }
            });
        }
        
        // 生成时间标签
        function generateTimeLabels() {
            const labels = [];
            for (let i = 23; i >= 0; i--) {
                const time = new Date();
                time.setHours(time.getHours() - i);
                labels.push(time.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }));
            }
            return labels;
        }
        
        // 生成随机数据
        function generateRandomData(count) {
            return Array.from({ length: count }, () => Math.floor(Math.random() * 100) + 50);
        }
        
        // 显示通知
        function showNotification(message, type = 'info') {
            const colors = {
                success: '#27ae60',
                error: '#e74c3c',
                warning: '#f39c12',
                info: '#3498db'
            };
            
            // 简单的通知实现
            console.log(`[${type.toUpperCase()}] ${message}`);
            
            // 这里可以集成更高级的通知库，如 toastr 或 sweetalert
        }
        
        // 页面初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 更新时间
            updateTime();
            setInterval(updateTime, 1000);
            
            // 初始化图表
            initChart();
            
            // 初始加载数据
            refreshAllData();
            
            // 设置定时刷新
            refreshInterval = setInterval(() => {
                refreshDevices();
                loadAlarms();
                updateSystemStats();
            }, 15000); // 15秒刷新一次
            
            // 页面卸载时清理
            window.addEventListener('beforeunload', () => {
                if (refreshInterval) {
                    clearInterval(refreshInterval);
                }
            });
            
            // 添加键盘快捷键
            document.addEventListener('keydown', (e) => {
                if (e.ctrlKey && e.key === 'r') {
                    e.preventDefault();
                    refreshAllData();
                }
            });
        });
    </script>
</body>
</html> 